<?php
namespace Common\Model;

class PlanWeekDayLimitModel extends Model {
    protected $tableName = 'acl';

    const TYPE  = 'week_day_limit';
    const OTYPE = 'plan';

    public function save2($d) {
        $planId = empty($d['planid']) ? 0 : $d['planid'];

        if(empty($planId)) {
            throw new ThinkException('没有计划编号，无法保存周限制数据');
        }

        $this->del($planId);

        if(!isset($d['week_day_limit'])) {
            return true;
        }

        $include = (int)$d['week_day_limit'];

        if($include == -1) {
            return true;
        }

        $include = empty($include) ? 0 : 1;

        if(empty($d['week_day_limit_item']) || !is_array($d['week_day_limit_item'])) {
            throw new ThinkException('请选择时间段');
        }

        $dao = array(
            'type'    => self::TYPE,
            'otype'   => self::OTYPE,
            'oid2'    => $planId,
            'include' => $include,
            'data'    => implode(',', $d['week_day_limit_item'])
        );

        if(!$this->add($dao)) {
            throw new ThinkException('按周投放限制信息保存出错');
        }

        return true;
    }

    public function getByPlanId($id) {
        $id = (int)$id;
        $expr = array(
            'type'  => self::TYPE,
            'otype' => self::OTYPE,
            'oid2'  => $id,
        );

        if($r = $this->where($expr)->find()) {
            $r['data'] = explode(',', $r['data']);
        }

        return $r;
    }

    /**
     * del
     *
     * @param mixed $id
     * @return void
     */
    public function del($planId) {
        $planId = (int)$planId;

        if(empty($planId)) {
            return true;
        }

        $expr = array(
            'type'  => self::TYPE,
            'otype' => self::OTYPE,
            'oid2'  => $planId,
        );

        return $this->where($expr)->delete();
    }

}
